#include "stdafx.h"
#include "KeybdEvent.h"

void CKeybdEvent::SingleStroke(HWND/* hWnd*/, WORD wVk, WORD wScan/* = 0*/)
{
	CKeybdEvent keybdEvent(wVk, wScan);
}

void CKeybdEvent::Combine2Strokes(HWND/* hWnd*/, WORD wVk1,WORD wVk2, WORD wScan1/* = 0*/, WORD wScan2/* = 0*/)
{
	BYTE rgbKeyState[256];
	::GetKeyboardState(rgbKeyState);
	{
		CKeybdEvent keybdEvent(wVk1, wScan1);
		rgbKeyState[wVk1] |= SHIFTED;
		::SetKeyboardState(rgbKeyState);
		{
			CKeybdEvent keybdEvent(wVk2, wScan2);
		}
	}
	rgbKeyState[wVk1] &= ~SHIFTED;
	::SetKeyboardState(rgbKeyState);
}

void CKeybdEvent::Combine3Strokes(HWND/* hWnd*/, WORD wVk1, WORD wVk2, WORD wVk3, WORD wScan1/* = 0*/, WORD wScan2/* = 0*/, WORD wScan3/* = 0*/)
{
	BYTE rgbKeyState[256];
	::GetKeyboardState(rgbKeyState);
	{
		CKeybdEvent keybdEvent(wVk1, wScan1);
		rgbKeyState[wVk1] |= SHIFTED;
		::SetKeyboardState(rgbKeyState);
		{
			CKeybdEvent keybdEvent(wVk2, wScan2);
			rgbKeyState[wVk2] |= SHIFTED;
			::SetKeyboardState(rgbKeyState);
			{
				CKeybdEvent keybdEvent(wVk3, wScan3);
			}
		}
	}
	rgbKeyState[wVk1] &= ~SHIFTED;
	rgbKeyState[wVk2] &= ~SHIFTED;
	::SetKeyboardState(rgbKeyState);
}

#if (_WIN32_WINNT > 0x0400)

CKeybdEvent::CKeybdEvent(WORD wVk, WORD wScan/* = 0*/, DWORD dwFlags/* = 0*/, DWORD time/* = 0*/, ULONG_PTR dwExtraInfo/* = NULL*/)
{
	if(0 == wScan)
	{
		HKL dwHkl = ::GetKeyboardLayout( ::GetCurrentThreadId() ) ;
		wScan = (WORD)::MapVirtualKeyEx((UINT)wVk, 0, dwHkl);
	}

	::ZeroMemory(&m_keybd_event, sizeof(INPUT) );
	m_keybd_event.type = INPUT_KEYBOARD;
	m_keybd_event.ki.wVk = wVk;
	m_keybd_event.ki.wScan = wScan;
	m_keybd_event.ki.dwFlags = dwFlags & ~(KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE);
	m_keybd_event.ki.dwExtraInfo = dwExtraInfo;
	
	::SendInput(1, &m_keybd_event, sizeof(INPUT));
}

CKeybdEvent::~CKeybdEvent()
{
	m_keybd_event.ki.dwFlags |= KEYEVENTF_KEYUP;
	::SendInput(1, &m_keybd_event, sizeof(INPUT));
}

#else	// #if (_WIN32_WINNT > 0x0400)

SHORT CKeybdEvent::VkKeyScan(TCHAR ch)
{
	HKL dwHkl = ::GetKeyboardLayout( ::GetCurrentThreadId() );

	return ::VkKeyScanEx(ch, dwHkl);
}

CKeybdEvent::CKeybdEvent(WORD wVk, WORD wScan, DWORD dwFlags/* = 0*/, DWORD time/* = 0*/, ULONG_PTR dwExtraInfo/* = NULL*/)
: m_bVk( (BYTE)wVk ), m_bScan( (BYTE)wScan ), m_dwFlags( dwFlags ), m_dwExtraInfo( dwExtraInfo )
{
	time;

	if(0 == m_bScan)
	{
		HKL dwHkl = ::GetKeyboardLayout( ::GetCurrentThreadId() ) ;
		m_bScan = (BYTE)::MapVirtualKeyEx((UINT)wVk, 0, dwHkl);
	}

	m_dwFlags &= ~KEYEVENTF_KEYUP;
	::keybd_event( m_bVk, m_bScan, m_dwFlags, m_dwExtraInfo );
}

CKeybdEvent::~CKeybdEvent()
{
	m_dwFlags |= KEYEVENTF_KEYUP;
	::keybd_event( m_bVk, m_bScan, m_dwFlags, m_dwExtraInfo );
}

#endif	// #if (_WIN32_WINNT > 0x0400)
